package com.example.androidservicetutorial;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.androidservicetutorial.service.BindService;

public class BindActivity extends AppCompatActivity {
    private final String TAG = getClass().getSimpleName();
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            BindService.LocalBinder binder = (BindService.LocalBinder) service;
            bindService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bindService = null;
        }
    };
    private BindService bindService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind);
        bindService = new BindService();
        final Intent intent = new Intent(this,BindService.class);
        final Button btnBindService = findViewById(R.id.btnBindService);
        btnBindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG,"绑定调用：bindService");
                bindService(intent,connection, Service.BIND_AUTO_CREATE);
            }
        });

        final Button btnUnbindService = findViewById(R.id.btnUnbindService);
        btnUnbindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG,"接触绑定调用：unbindService");
                if (bindService != null) {
                    bindService = null;
                    unbindService(connection);
                }
            }
        });

        final Button btnGetData = findViewById(R.id.btnGetData);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bindService != null) {
                    int count = bindService.getCount();
                    Toast.makeText(BindActivity.this, "从服务端获取的数据是：" + count, Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(BindActivity.this, "还没绑定呢,请先绑定", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}